--[[ SLDataText Copyright (c) 2008, Jeff "Taffu" Fancher <jdfancher@gmail.com> All rights reserved. ]]
-- Version: 2.1.4 -- Rev Date: 11/09/2008

local SLDataText = LibStub("AceAddon-3.0"):GetAddon("SLDataText")
local L = LibStub("AceLocale-3.0"):GetLocale("SLDataText")
local media = LibStub("LibSharedMedia-3.0")
local justTable, strataTable, pointTable = SLDataText.just, SLDataText.strata, SLDataText.point
local db

local MODNAME = "Calendar"
local Calendar = SLDataText:NewModule(MODNAME, "AceEvent-3.0")

local optGetter, optSetter
do
	function optGetter(info)
		local key = info[#info]
		return db[key]
	end

	function optSetter(info, value)
		local key = info[#info]
		db[key] = value
        SLDataText:RefreshModule(Calendar)
	end
end

local options
local function getOptions()
	if not options then
		options = {
			type = "group",
            name = L["Calendar"],
            arg = MODNAME,
            get = optGetter,
			set = optSetter,
            args = {
                genHeader = {
                    type = "header",
                    name = L["GenCalSet"],
                    order = 25,
                },
                enabled = {
                    type = "toggle",
                    name = L["Enabled"],
                    desc = L["EnabledDesc"],
                    get = function() return SLDataText:GetModuleEnabled(MODNAME) end,
					set = function(info, value) 
                        SLDataText:SetModuleEnabled(MODNAME, value)
                        if ( SLDataText:GetModuleEnabled(MODNAME) ) then
                            Calendar:PLAYER_ENTERING_WORLD()
                        end
                    end,
                    order = 50,
                },
                hideTooltip = {
                    type = "toggle",
                    name = L["HideTT"],
                    desc = L["HideTTDesc"],
                    order = 125,
                },
                noCombatHide = {
                    type = "toggle",
                    name = L["SIC"],
                    desc = L["SICDesc"],
                    order = 150,
                },
                dispHeader = {
                    type = "header",
                    name = L["DispSet"],
                    order = 275,
                },
                useGlobalFont = {
                    type = "toggle",
                    name = L["UseGblFont"],
                    desc = L["UseGblFontDesc"],
                    order = 300,
                },
                useGlobalFontSize = {
                    type = "toggle",
                    name = L["UseGblFSize"],
                    desc = L["UseGblFSizeDesc"],
                    order = 350,
                },
                fontFace = {
                    type = "select",
                    name = L["Font"],
                    desc = L["FontDesc"],
                    disabled = function()
                        local isTrue
                        if ( db.useGlobalFont ) then isTrue = true else isTrue = false end
                        return isTrue
                    end,
                    values = media:List("font"),
                    get = function()
                        for k, v in pairs(media:List("font")) do
                            if db.fontFace == v then
                                return k
                            end
                        end
                    end,
                    set = function(_, font)
                        local list = media:List("font")
                        db.fontFace = list[font]
                        SLDataText:RefreshModule(Calendar)
                    end,
                    width = "double",
                    order = 600,
                },
                fontSize = {
                    type = "range",
                    name = L["FontSize"],
                    desc = L["FontSizeDesc"],
                    disabled = function()
                        local isTrue
                        if ( db.useGlobalFontSize ) then isTrue = true else isTrue = false end
                        return isTrue
                    end,
                    min = 6, max = 36, step = 1,
                    width = "double",
                    order = 650,
                },
                posHeader = {
                    type = "header",
                    name = L["LaySet"],
                    order = 700,
                },
                justify = {
                    type = "select",
                    name = L["TextJust"],
                    desc = L["TextJustDesc"],
                    values = justTable,
                    width = "double",
                    order = 750,
                },
                anchor = {
                    type = "input",
                    name = L["ParFrm"],
                    desc = L["ParFrmDesc"],
                    get = function() return db.anchor end,
                    width = "double",
                    order = 800,
                },
                anchorFrom = {
                    type = "select",
                    name = L["AnchFrom"],
                    desc = L["AnchFromDesc"],
                    values = pointTable,
                    get = function() return db.anchorFrom end,
                    width = "double",
                    order = 900,
                },
                offX = {
                    type = "input",
                    name = L["XOff"],
                    desc = L["XOffDesc"],
                    get = function() return tostring(db.offX) end,
                    width = "double",
                    order = 1000,
                },
                offY = {
                    type = "input",
                    name = L["YOff"],
                    desc = L["YOffDesc"],
                    get = function() return tostring(db.offY) end,
                    width = "double",
                    order = 1100,
                },
                strata = {
                    type = "select",
                    name = L["Strata"],
                    desc = L["StrataDesc"],
                    values = strataTable,
                    width = "double",
                    order = 1600,
                },
            },
		}
	end
	
	return options
end

local pulseDown = true
local function invitePulse(self, invites)
    self.pulse:SetBackdrop({
        bgFile = "Interface\\Addons\\SLDataText\\Media\\Pulse.tga", tile = false,
        insets = { left = 0, top = 0, right = 0, bottom = 0 },
    })
    self.pulse:SetAllPoints(self.frame)
    
    if ( invites == 0 ) then
        self.pulse:SetScript("OnUpdate", nil)
        if ( self.pulse:IsShown() ) then self.pulse:Hide() end
    else
        self.pulse:SetScript("OnUpdate", function(self, elapsed)
            local step = abs(1/30)
            if ( self:GetAlpha() == 1 ) then
                pulseDown = true
                self:SetAlpha(self:GetAlpha()-step)
            elseif ( self:GetAlpha() == 0 ) then
                pulseDown = false
                self:SetAlpha(self:GetAlpha()+step)
            else
                if ( pulseDown ) then
                    self:SetAlpha(self:GetAlpha()-step)
                else
                    self:SetAlpha(self:GetAlpha()+step)
                end
            end
        end)
    end
end

local function buildModule(self)
    if ( not self.frame ) then self.frame = CreateFrame("Frame", "SLDT_Calendar", UIParent) end
    if ( not self.button ) then self.button = CreateFrame("Button", nil, self.frame) end
    if ( not self.pulse ) then self.pulse = CreateFrame("Frame", nil, self.frame) end
    if ( not self.string ) then self.string = self.frame:CreateFontString(nil, "OVERLAY") end
    
    self.button:SetScript("OnClick", function()
        ToggleCalendar()
    end)
    
    Calendar:RegisterEvent("PLAYER_ENTERING_WORLD")
end

function Calendar:PLAYER_ENTERING_WORLD()
    SLDataText:RefreshModule(self)
    self:UnregisterEvent("PLAYER_ENTERING_WORLD")
end

function Calendar:OnInitialize()
	self.db = SLDataText.db:RegisterNamespace(MODNAME)
    self.db:RegisterDefaults({
        profile = {
            hideTooltip = false,
            noCombatHide = false,
            fontFace = "Arial Narrow",
            useGlobalFont = true,
            fontSize = 12,
            useGlobalFontSize = true,
            justify = "CENTER",
            anchorPoint = "CENTER", 
            anchor = "Minimap", 
            anchorFrom = "BOTTOM", 
            offX = 0, 
            offY = -28,
            strata = "BACKGROUND",
        },
    })
	db = self.db.profile
    
    if ( not self.isMoving ) then self.isMoving = false end
	self:SetEnabledState(SLDataText:GetModuleEnabled(MODNAME))
	SLDataText:RegisterModuleOptions(MODNAME, getOptions)
end

function Calendar:OnEnable()
    self:RegisterEvent("CALENDAR_UPDATE_PENDING_INVITES", "Refresh")
    buildModule(self)
    if ( GameTimeFrame and GameTimeFrame:IsShown() ) then GameTimeFrame:Hide() end
    if ( not self.frame:IsShown() ) then self.frame:Show() end
end

function Calendar:OnDisable()
    self:UnregisterEvent("CALENDAR_UPDATE_PENDING_INVITES")
    self:UnregisterEvent("PLAYER_ENTERING_WORLD")
    self.frame:SetScript("OnUpdate", nil)
    self.button:SetScript("OnClick", nil)
    if ( GameTimeFrame and not GameTimeFrame:IsShown() ) then GameTimeFrame:Show() end
	if ( self.frame:IsShown() ) then self.frame:Hide() end
end

function Calendar:Refresh()
    local invites = CalendarGetNumPendingInvites()
    invitePulse(self, invites)
    local text = date("%B %d (%a)")
    
    if ( SLDataText.db.profile.locked and not db.hideTooltip ) then
        self.button:EnableMouse(true)
        self.button:SetScript("OnEnter", function()
            GameTooltip:SetOwner(this, "ANCHOR_CURSOR")
            GameTooltip:AddLine(format("%s%s|r", "|cffffff00", L["CalInfo"]))
            GameTooltip:AddLine(text)
            GameTooltip:AddDoubleLine(" ")
            if ( invites > 0 ) then
                GameTooltip:AddDoubleLine(L["PendInv"], invites, 1, 1, 1, 1, 1, 1)
                GameTooltip:AddLine(" ")
            end
            GameTooltip:AddLine(L["CalHint"])
            GameTooltip:Show()
        end)
        self.button:SetScript("OnLeave", function()
            if ( GameTooltip:IsShown() ) then GameTooltip:Hide() end
        end)
    else
        self.button:EnableMouse(false)
        self.button:SetScript("OnEnter", nil)
        self.button:SetScript("OnLeave", nil)
    end
    
    self.string:SetText(text)
    
    SLDataText:UpdateModule(self)
end